package com.tanhua.dubbo.api;

import cn.hutool.core.date.DateUtil;
import com.tanhua.dubbo.api.mongo.VisitorApi;
import com.tanhua.model.mongo.Visitors;
import net.sf.jsqlparser.statement.create.index.CreateIndex;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.Date;
import java.util.List;

@DubboService
public class VisitorApiImpl implements VisitorApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存访客记录
     *
     * @param visitors
     */
    @Override
    public void save(Visitors visitors) {
        // 每人每天只有一条记录
        String today = DateUtil.format(new Date(), "yyyyMMdd");
        // 判断是否存在，条件userId=佳人id, visitorUserId=访客id, 访问日期=今天
        Query query = new Query(Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(today)
        );
        if (mongoTemplate.exists(query, Visitors.class)) {
            // 存在则更新 date
            Update update = new Update();
            update.set("from", visitors.getFrom());
            update.set("date", System.currentTimeMillis());
            mongoTemplate.updateFirst(query, update, Visitors.class);
        }else{
        // 不存在则添加
            visitors.setDate(System.currentTimeMillis());
            visitors.setVisitDate(today);
            mongoTemplate.insert(visitors);
        }
    }

    /**
     * 首页中的 最近访客
     *
     * @param loginUserId
     * @param lastTime
     * @return
     */
    @Override
    public List<Visitors> findLast4Visitors(Long loginUserId, String lastTime) {
        //1. 构建查询条件userId=loginUserId,
        Query query = new Query(Criteria.where("userId").is(loginUserId));
        //如果lastTime有值，则添加条件date>lastTime
        if(StringUtils.isNotEmpty(lastTime)){
            query.addCriteria(Criteria.where("date").gt(Long.valueOf(lastTime)));
        }
        //2. 降序date
        query.with(Sort.by(Sort.Order.desc("date")));
        //3. 设置分页参数，skip(0).limit(4)，取最新的4条记录
        query.skip(0).limit(4);
        //4. 查询返回
        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);
        return visitors;
    }
}
